package org.example.todolist.service.impl;

import lombok.RequiredArgsConstructor;
import org.example.todolist.config.Config;
import org.example.todolist.entity.User;
import org.example.todolist.mapper.UserMapper;
import org.example.todolist.service.UserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.HexFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {
    private final Config config;
    private final UserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public User register(User user) throws NoSuchAlgorithmException {
        // 检查用户名是否已存在
        if (checkUsername(user.getUsername())) {
            return null;
        }
        // 检查邮箱是否已存在
        if (checkEmail(user.getEmail())) {
            return null;
        }
        // 设置创建时间
        user.setCreatedAt(LocalDateTime.now());

//        // 使用MD5加密密码
//        MessageDigest md5 = MessageDigest.getInstance("MD5");
//        md5.update((user.getPassword() + config.getSalt()).getBytes());
//
//        user.setPassword(HexFormat.of().formatHex(md5.digest()));

        String hashed = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        //使用BCrypt加密密码
        user.setPassword(hashed);
        // 插入用户
        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return null;
        }
        return user;
    }

    @Override
    public User login(String username, String password) {

        // 根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        //解密
        if (BCrypt.checkpw(password, user.getPassword())){
            return user;
        }
        else
            return null;


//        return  userMapper.login(username, password);

    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public boolean updateUser(User user) {
        int resultCount = userMapper.update(user);
        return resultCount > 0;
    }

    @Override
    public boolean checkUsername(String username) {
        int resultCount = userMapper.checkUsername(username);
        return resultCount > 0;
    }

    @Override
    public boolean checkEmail(String email) {
        int resultCount = userMapper.checkEmail(email);
        return resultCount > 0;
    }
}
